package com.hedl.classroom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hedl.classroom.base.exception.CommonResult;
import com.hedl.classroom.base.exception.OnlinecClassroomException;
import com.hedl.classroom.mapper.CourseTeacherMapper;
import com.hedl.classroom.model.po.CourseTeacher;
import com.hedl.classroom.service.CourseTeacherService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class CourseTeacherServiceImpl implements CourseTeacherService {

    @Resource
    private CourseTeacherMapper courseTeacherMapper;

    @Override
    public List<CourseTeacher> queryCourseTeacher(Long courseId) {
        if (courseId == null) {
            OnlinecClassroomException.cast("课程id为空！");
        }
        LambdaQueryWrapper<CourseTeacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseTeacher::getCourseId,courseId);
        List<CourseTeacher> courseTeachers = courseTeacherMapper.selectList(queryWrapper);
        return courseTeachers;
    }

    @Override
    @Transactional
    public CourseTeacher saveCourseTeacher(CourseTeacher courseTeacher) {
        if (courseTeacher == null){
            OnlinecClassroomException.cast("新增数据为空！");
        }
        Long id = courseTeacher.getId();
        if (id == null){
            return addCourseTeacher(courseTeacher);
        }else{
            courseTeacherMapper.deleteById(id);
            return addCourseTeacher(courseTeacher);
        }
    }

    private CourseTeacher addCourseTeacher(CourseTeacher courseTeacher){
        courseTeacher.setCreateDate(LocalDateTime.now());
        if (courseTeacher.getId() != null){
            courseTeacher.setId(null);
        }
        int insert = courseTeacherMapper.insert(courseTeacher);
        if (insert <= 0){
            OnlinecClassroomException.cast("新增失败！");
        }else {
            CourseTeacher courseTeacher1 = courseTeacherMapper.selectById(courseTeacher.getId());
            return courseTeacher1;
        }
        return null;
    }

    @Override
    public CommonResult deleteTeacher(Long courseId, Long teacherId) {
        LambdaQueryWrapper<CourseTeacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseTeacher::getCourseId,courseId);
        queryWrapper.eq(CourseTeacher::getId,teacherId);
        List<CourseTeacher> courseTeachers = courseTeacherMapper.selectList(queryWrapper);
        if (courseTeachers.equals("")){
            OnlinecClassroomException.cast("查无此人！");
        }
        int delete = courseTeacherMapper.delete(queryWrapper);
        if (delete <= 0){
            return CommonResult.error("删除失败");
        }
        return CommonResult.result();
    }
}
